<template>
  <view :style="colorStyle" class="wrap">
    <view class="header">
      <view class="logo_name flex_s">
        <!-- <view class="logo_box">
            <image :src="logoImg" mode="aspectFill" v-if="logoImg" />
            <image src="@/static/image/logo.png" mode="aspectFill" v-else />
          </view> -->
        <text v-if="enterprise_name_show">{{ enterprise_name }}</text>
      </view>
      <!-- <view class="extra_box flex_s">
        <view class="share_box flex_c" @click="shareMasker = true">
          <text class="iconfont icon-fenxiang"></text>
        </view>
      </view> -->

      <view class="swiper_box" :class="{ minHeight: !bannerList.length }">
        <swiper
          :style="'height:' + imageH + 'px;'"
          class="swiper"
          circular
          :autoplay="true"
        >
          <swiper-item
            v-for="(item, index) in bannerList"
            :key="index"
            @click="bannerClick(item)"
          >
            <view class="masker"></view>
            <view class="swiper_item">
              <image :src="item.images" mode="widthFix" />
            </view>
          </swiper-item>
        </swiper>
      </view>
      <view class="menu_box flex_se">
        <view class="open_right">
          <view class="top_time_box">
            <view>{{ currentTimeDate }}</view>
            <view>{{ currentTimeHour }}</view>
          </view>

          <view class="top_status_box flex_s">
            <view class="status_box pad10" v-if="is_business_status">开盘</view>
            <view class="status_box close_status pad10" v-else>闭盘</view>
            <view class="status_text pad10">实时金价</view>
          </view>
        </view>
      </view>
    </view>

    <view class="container">
      <template v-for="(item, index) in tableData" :key="index">
        <view class="tabale_item" v-if="item.list.length">
          <view class="tabale_title" v-if="item.title"> {{ item.title }} </view>
          <view class="table_box">
            <uni-table ref="table" stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th
                  width="87"
                  align="center"
                  v-for="(item, index) in item.thList"
                  :key="index"
                >
                  <view class="table_th"> {{ item.name }} </view>
                </uni-th>
              </uni-tr>

              <uni-tr v-for="(_item, _index) in item.list" :key="_index">
                <uni-td align="center">
                  <view class="table_td name_td">{{ _item.name }}</view>
                </uni-td>
                <uni-td align="center">
                  <view
                    class="table_td"
                    :class="[
                      { colorRed: _item.askprice_one_color == 1 },
                      { colorGreen: _item.askprice_one_color == 2 },
                      {
                        colorGreenLight:
                          Cache.get('themeValue') &&
                          Cache.get('themeValue') == 'dark',
                      },
                    ]"
                  >
                    {{ _item.askprice_one }}
                  </view>
                </uni-td>
                <uni-td align="center">
                  <view
                    class="table_td"
                    :class="[
                      { colorRed: _item.askprice_two_color == 1 },
                      { colorGreen: _item.askprice_two_color == 2 },
                      {
                        colorGreenLight:
                          Cache.get('themeValue') &&
                          Cache.get('themeValue') == 'dark',
                      },
                    ]"
                  >
                    {{ _item.askprice_two }}
                  </view>
                </uni-td>
                <uni-td align="center">
                  <view
                    class="table_td black_color"
                    :class="[
                      {
                        white_color:
                          Cache.get('themeValue') &&
                          Cache.get('themeValue') == 'dark',
                      },
                    ]"
                  >
                    {{ _item.basis_spread }}
                  </view>
                </uni-td>
              </uni-tr>
            </uni-table>
          </view>
        </view>
      </template>
    </view>
    <view class="footer">
      <view class="text_item">
        <text>声明：</text><text class="red_class">以上行情仅供参考！</text>
      </view>
    </view>
    <view class="uni-p-b-98"></view>
    <pageFooter
      :is_gold_basis="is_gold_basis"
      :is_money_remind="is_money_remind"
      :shareData="shareData"
      :isShowAllMenu="isShowAllMenu"
      :selected="3"
    ></pageFooter>
  </view>
</template>

<script setup lang="ts">
import wechatEnv from "@/utils/getWechatEnvironment.js";
import pageFooter from "@/components/pageFooter/index.vue";
import { watch } from "vue";
import { onLoad, onUnload, onHide, onShow } from "@dcloudio/uni-app";
import { useTheme } from "@/composables/useTheme";
import { JumpPath, timeFormat, Tips, isWeixin } from "@/utils";
import { checkLogin, toLogin } from "@/libs/login";
import { marketGet, getGebasisSpreadt } from "@/api/home";
import Cache from "@/utils/cache";
import { USER_INFO, LOGIN_STATUS } from "@/config/cache";
import { getWechatShare } from "@/api/public";
import { getUserInfo, getCurlOauth, getOpenidByCode } from "@/api/user";
import { useTokenStore } from "@/store/index";
import wx from "weixin-js-sdk";
import themeList from "@/utils/theme";
// websocket 通讯
let websocketUtil = inject("websocketUtil");
const { colorStyle } = useTheme();
onHide(() => {
  clearInterval(timer.value);
});
onUnload(() => {
  clearInterval(timer.value);
});
let logImg = ref("");
let isShowAllMenu = ref(false);
let shareData = ref({
  business_id: "",
  urltype: "",
});
onLoad((option) => {
  // 分享进来的存储，底部菜单区分
  if (option.business_id) {
    shareData.value.business_id = option.business_id;
    shareData.value.urltype = option.urltype;
    Cache.set("urltype", option.urltype);
    Cache.set("business_id", option.business_id);
    isShowAllMenu.value = false;
  }
});
let wechat_share = reactive({});
let home_url = ref("");
onShow(async () => {
  let { data } = await getWechatShare();
  wechat_share = data.wechat_share;
  home_url.value = data.home_url;
  if (isWeixin()) {
    // 微信浏览器环境需授权登录，token用于首页到价提醒功能操作
    setTokenHandler();
  }
  // 监听行情更新事件
  uni.$on("marketUpdate", (data) => {
    uni.hideLoading();
    setData(data);
    // console.log(data, "接收的数据");
  });
  if (Cache.get(USER_INFO)) {
    userInfo = JSON.parse(Cache.get(USER_INFO));
    logImg.value = userInfo.logo;
  }
  setShareHandler();
  getDataHandler();
  if (Cache.get("business_id")) {
    isShowAllMenu.value = false;
  } else {
    isShowAllMenu.value = true;
  }
});

// 获取公众号授权链接并跳转
async function getCurlOauthHandler() {
  let redirect_url = `${home_url.value}/pages/tabbar/basis`;
  if (Cache.get("business_id")) {
    redirect_url += `?business_id=${Cache.get("business_id")}`;
  }
  if (Cache.get("urltype")) {
    redirect_url += `&urltype=${Cache.get("urltype")}`;
  }
  let params = { mode: 0, source: redirect_url };
  let res = await getCurlOauth(params);
  let { auth_url } = res.data;
  window.location = auth_url;
}
async function setTokenHandler() {
  const token = uni.getStorageSync(LOGIN_STATUS);
  var url = window.location.href;
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(url.indexOf("?") + 1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }

  if (theRequest.code) {
    // 存在code时，调用接口获取token
    // 使用code和state调用接口获取普通用户的token

    let res = await getOpenidByCode({
      code: theRequest.code,
      state: theRequest.state,
    });
    let { data, code, info } = res;
    let token = data.token.token;
    const tokenStore = useTokenStore();
    await tokenStore.setToken(token);
    if (code != 1) {
      return Tips({
        title: info,
      });
    }

    return;
  }
  if (!token) {
    //没有授权token 时，获取跳转链接让用户授权公众号登录获取code
    getCurlOauthHandler();
    return;
  }
}
let userInfo = reactive({});

function setShareHandler() {
  wx.ready(async () => {
    wx.showAllNonBaseMenuItem();
    wx.hideMenuItems({
      menuList: ["menuItem:copyUrl"], // 屏蔽复制链接
    });

    try {
      let link = `${home_url.value}/pages/tabbar/basis?business_id=${
        shareData.value.business_id || userInfo.id
      }&urltype=share`;
      let imgUrl = wechat_share.image;
      let title = "";
      if (wechat_share.is_type_img == 1) {
        // 使用系统图片
        // imgUrl = wechat_share.image;
        title = wechat_share.title;
      } else {
        // imgUrl = userInfo.logo;
        title = userInfo.enterprise_name;
      }
      // 分享个人
      wx.updateAppMessageShareData({
        title: title, // 分享标题
        desc: wechat_share.introduction, // 分享描述
        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: imgUrl, // 分享图标
        success: function () {
          console.log("分享设置成功");

          // 设置成功
        },
        fail: function (res) {
          // 微信PC端情况下失败刷新当前页面

          if (wechatEnv.isDesktop) location.reload();
        },
      });
      // 分享朋友圈
      wx.updateTimelineShareData({
        title: title || "", // 分享标题
        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: imgUrl, // 分享图标
        success: function () {
          // 设置成功
        },
      });
      wx.error(function (res) {
        alert(res.errMsg);
      });
    } catch (error) {
      console.log("隐藏微信菜单失败:", error);
    }
  });
}
let timer = ref(null);
function getDataHandler() {
  let params = {
    business_id: shareData.value.business_id || userInfo.id,
    is_type: "basis",
    message: JSON.stringify("金价请求"),
  };

  websocketUtil.sendMsg(params);
  clearInterval(timer.value);
  timer.value = setInterval(() => {
    getDataHandler();
  }, 1000);
}

let currentTime = ref("");
let currentTimeDate = ref("");
let currentTimeHour = ref("");
function getCurrentTime() {
  currentTime.value = timeFormat(new Date(), "yyyy-mm-dd hh:MM:ss");
  let dateArr = currentTime.value.split(" ");
  currentTimeDate.value = dateArr[0];
  currentTimeHour.value = dateArr[1];
}
let marketList = ref({});
let is_business_status = ref(true);
let is_money_remind = ref(false);
let is_gold_basis = ref(false);
let bannerList = ref([]);
let enterprise_name_show = ref(0); //企业名称展示
let enterprise_name = ref(""); //企业名称
function setData(res) {
  getCurrentTime();
  const { data } = res;

  marketList.value = data.marketList;
  setTabalDataHandler();

  const busione = data.busione;
  if (!busione) return;
  is_business_status.value = !!busione.is_business_status;
  is_money_remind.value = !!+busione.is_money_remind;
  is_gold_basis.value = !!+busione.is_gold_basis;
  bannerList.value = busione.banna;
  if (bannerList.value.length) setSwiperHeight();
  enterprise_name.value = busione.enterprise_name;
  enterprise_name_show.value = busione.enterprise_name_show;
  let theme1 = busione.theme ? busione.theme : "dark";
  let theme2 = busione.theme_colour ? busione.theme_colour : "golden";
  setThemeHandler(theme1, theme2);
}
function setTabalDataHandler() {
  for (const key in marketList.value) {
    tableData.value.forEach((item) => {
      if (item.id == key) {
        item.list = marketList.value[key];
      }
    });
  }
}
// 设置主题样式
function setThemeHandler(themeValue, subThemeValue = "golden") {
  // 合并默认主题
  const mergedTheme =
    themeList["theme"][themeValue] + themeList["sub_theme"][subThemeValue];
  uni.setStorageSync("viewColor", mergedTheme);
  uni.setStorageSync("themeValue", themeValue);
  // 更新响应式变量以触发页面样式更新
  colorStyle.value = mergedTheme;
}
let tableData = ref([
  {
    id: "first_block",
    title: "",
    list: [],
    thList: [
      { name: "商品" },
      {
        name: "水贝买价",
      },
      {
        name: "国际卖价",
      },
      {
        name: "基差",
      },
    ],
  },
  {
    id: "second_block",
    title: "上金价VS国际价",
    list: [],
    thList: [
      { name: "商品" },
      {
        name: "上金价",
      },
      {
        name: "国际卖价",
      },
      {
        name: "基差",
      },
    ],
  },
  {
    id: "third_block",
    title: "上期价VS国际价",
    list: [],
    thList: [
      { name: "商品" },
      {
        name: "上期价",
      },
      {
        name: "国际卖价",
      },
      {
        name: "基差",
      },
    ],
  },
  {
    id: "four_block",
    title: "金银比",
    list: [],
    thList: [
      { name: "商品" },
      {
        name: "国际金卖价",
      },
      {
        name: "国际银买价",
      },
      {
        name: "金银比",
      },
    ],
  },
]);
function setSwiperHeight() {
  uni.getImageInfo({
    src: bannerList.value.length && bannerList.value[0].images,
    success: function (res) {
      imageH.value = res.height;
    },
  });
}
let imageH = ref(0);
watch(
  () => imageH,
  (nVal, oVal) => {
    imageH.value = nVal;
  }
);
</script>

<style scoped lang="scss">
::v-deep .uni-table {
  min-width: auto !important;
  background: unset !important;
  // 改表头字体样式
  .uni-table-th {
    border: none;
    border-right: 1px solid var(--view-td-right);
    background: var(--view-th1-color);
    font-size: 24rpx;
    font-weight: normal;
    color: var(--view-th-font-color);
  }
  .table--border {
    border: none;
  }
  .uni-table-td {
    border: none;
    border-right: 1px solid var(--view-td-right);
    padding-top: 20rpx;
    padding-bottom: 20rpx;
  }
  .uni-table-tr:nth-child(2n + 2),
  .uni-table-tr:nth-child(2n + 2):hover {
    background: var(--view-th2-color);
  }
  .uni-table-tr:nth-child(2n + 3),
  .uni-table-tr:nth-child(2n + 3):hover {
    background: var(--view-th3-color);
  }
}
.wrap {
  // max-width: 750rpx;
  margin: 0 auto;
  // padding-top: 300rpx;
  min-height: 100vh;
  background: var(--view-linear-home-bg);
  position: relative;
  .header {
    position: relative;
    width: 100%;
    margin-bottom: 30rpx;
    // height: 370rpx;
    height: auto;
    .top_box,
    .menu_box {
      position: absolute;

      z-index: 99;
      right: 10rpx;
      // transform: translateX(-50%);
      bottom: 10rpx;
      // width: 700rpx;
      border-radius: 16rpx;
      // box-shadow: 0px 4rpx 20rpx 0px rgba(220, 202, 156, 0.3);
      // background: var(--view-linear-home);
      .top_item {
        font-size: 24rpx;
        color: var(--view-fontColor);
        .iconfont {
          font-size: 24rpx;
          margin-right: 5rpx;
        }
      }
      .open_right {
        overflow: hidden;
        .top_time_box {
          text-align: center;
          color: var(--view-tabale-title);
          line-height: 40rpx;
          font-size: 26rpx;
        }
        .top_status_box {
          margin-top: 10rpx;
          font-size: 20rpx;
          color: var(--view-tabale-title);
          .status_box {
            color: #fff;
            border-top-left-radius: 10rpx;
            border-bottom-left-radius: 10rpx;
            background: #d43030;
            border: 1px solid var(--view-border-color);
            border-right: unset;
          }
          .close_status {
            background: #1d8c29;
          }
          .status_text {
            background: var(--view-status-bg);
            border-top-right-radius: 10rpx;
            border-bottom-right-radius: 10rpx;
            border: 1px solid var(--view-border-color);
            border-left: unset;
          }
        }
      }
    }
    .menu_item {
      color: #fff;
      font-size: 24rpx;
      margin-left: 20rpx;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 99rpx;
    }
    .minHeight {
      min-height: 150rpx !important;
    }
    .swiper_box {
      position: relative;
      width: 100%;
      // height: 150rpx;
      min-height: 100rpx;
      // background: #fff;
      overflow: hidden;
      .masker {
        position: absolute;
        z-index: 10;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgb(0, 0, 0);
        opacity: 0.05;
      }
      .swiper_item {
        width: 100%;
        height: 100%;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
    .logo_name {
      position: absolute;
      z-index: 20;
      left: 24rpx;
      top: 30rpx;
      font-size: 30rpx;
      color: #fff;
      .logo_box {
        width: 80rpx;
        height: 80rpx;
        border: 2rpx solid #fff;
        border-radius: 8rpx;

        overflow: hidden;
        image {
          width: 100%;
          height: 100%;
        }
      }
      text {
        font-size: 64rpx;
        color: var(--view-logoName-color);
        font-weight: 600;
        // margin-left: 10rpx;
      }
    }
    .extra_box {
      z-index: 20;
      position: absolute;
      right: 10rpx;
      top: 10rpx;
      .extra_item {
        color: #fff;
        font-size: 24rpx;
        margin-left: 20rpx;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 99rpx;
        border: 2rpx solid #fff;
      }

      .share_box {
        width: 60rpx;
        height: 60rpx;
        color: #fff;
        padding: 10rpx 20rpx;
        border-radius: 50%;
        border: 2rpx solid #fff;
        background: rgba(0, 0, 0, 0.4);
        margin-left: 20rpx;
        .iconfont {
          color: #fff;
          font-size: 25rpx;
          font-weight: bold;
        }
      }
    }
  }

  .container {
    padding: 0 10rpx;
    position: relative;

    .table_box {
      // width: 720rpx;
      margin: 0 auto;
      border: 2px solid var(--view-tabale-border);
      border-radius: 16px;
      margin-bottom: 50rpx;
      // background: rgba(255, 255, 255, 0.45);
      font-family: "NotoSansSC";
      overflow: hidden;
      .table_th {
        font-size: 32rpx;
        font-weight: bold;
        white-space: nowrap;
      }
      .table_td {
        // font-weight: 600;
        font-size: 38rpx;
        line-height: 50rpx;
        color: rgb(247, 0, 0);
      }
      .black_color {
        color: #000;
      }
      .white_color {
        color: #fff;
      }
      .name_td {
        color: var(--view-tabale-title);
        font-size: 36rpx;
        font-weight: normal;
        white-space: nowrap;
      }
    }
    .tabale_title {
      color: var(--view-tabale-title);
      text-align: center;
      font-family: Source Han Serif CN;
      font-size: 34rpx;
      font-weight: bold;
      line-height: 43rpx;
      letter-spacing: 10rpx;
      text-align: center;
      margin-bottom: 26rpx;
    }
  }
}
.footer {
  padding: 0 20rpx;
  // width: 680rpx;
  margin: 0 auto;
  margin-top: 50rpx;
  font-size: 30rpx;
  color: var(--view-tabale-title);
  .red_class {
    color: #e91414;
  }
  .text_item {
    margin-right: 50rpx;
    margin-bottom: 20rpx;
    .iconfont {
      font-size: 30rpx;
      margin-right: 10rpx;
    }
  }
}
</style>
